package myJs.cps

import cats.effect.SyncIO
import myJs.myPkg.reactHookForm._
import org.scalajs.dom.{Event, html}
import japgolly.scalajs.react.vdom.all._
import japgolly.scalajs.react._
import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react.util.EffectCatsEffect._
import myJs.myPkg.Hooks._
import myJs.Utils._

/** Created by yz on 3/11/2020
  */
object PureToggleCp {

  case class Props(
      show: Boolean = true,
      name: String = "",
      value: Boolean,
      valueChange: Boolean => SyncIO[Unit],
      canChange:SyncIO[Boolean]=SyncIO(true)
  ){
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val useController = ReactHookForm.useController(options =
      UseControllerOptions(
        name = props.name,
        defaultValue = s"${props.value}"
      )
    )
    val field = useController.field

    object FTool {

      def defaultChange(checked: Boolean) = {
        props.canChange.flatMap{b=>
          if(b){
            field.onChange(s"${checked}")
            props.valueChange(checked)
          }else SyncIO.unit
        }
      }

      def onChange  (e: ReactEventFromInput) = {
        val v = e.target.value
        field.onChange(v)
        props.valueChange(v.toBoolean)
      }

    }

    val clsStr = if (props.value) "btn-primary" else "btn-light off"
    div(
      width := "62px", height := "35px",
      className := s"toggle btn ${clsStr}",
      dataToggle := "toggle",
      role := "button",
      input(
        height := "32px",
        className := "myToggle",
        `type` := "text",
        dataToggle := "toggle",
        dataOn := "Yes",
        dataOff := "No",
        name := field.name,
        className := "",
        width := "100px",
        value := s"${props.value}",
        onChange ==> FTool.onChange,
        vRef := field.ref
      ),
      div(
        className := "toggle-group",
        label(className := "btn btn-primary toggle-on", "Yes", onClick --> FTool.defaultChange(false)),
        label(className := "btn btn-light toggle-off", "No", onClick --> FTool.defaultChange(true)),
        span(className := "toggle-handle btn btn-light")
      )
    )

  }

}
